using System;
using System.Xml.Linq;
using System.Collections;
using System.Collections.Generic;

namespace DaphneTranslator.BusinessLogic
{
	/// <summary>
	/// Xml loader.
	/// </summary>
	public class XmlLoader: ILoader
	{
		private string keyAttrCulture = "Culture";
		private string keyNodeText = "Value";
		private string keyAttrId = "Id";
		private string keyAttrEnglishName = "EnglishName";
		private string keyAttrCultureName = "CultureName";
		
		public XmlLoader ()
		{
		}

		#region ILoader implementation
		
		/// <summary>
		/// loads the xml file
		/// </summary>
		public LanguageFile Load (string sFilePath)
		{
			LanguageFile list = new LanguageFile ();
			
			// open the file
			XDocument doc = XDocument.Load (sFilePath);
			
			// parse the culture
			string sCulture = doc.Root.Attribute (keyAttrCulture).Value;
			list.Culture = sCulture;
			list.EnglishName = doc.Root.Attribute (keyAttrEnglishName).Value;
			list.CultureName = doc.Root.Attribute (keyAttrCultureName).Value;
			
			foreach (XElement element in doc.Root.Descendants(keyNodeText)) {
				
				string sKey = element.Attribute (keyAttrId).Value;
				XAttribute attrText = GetTextAttribute (element);
				if (attrText == null)
					continue;
				
				LanguageText objText = new LanguageText ();
				objText.Key = sKey;
				objText.ValueXmlKey = attrText.Name.LocalName;
				objText.Value = attrText.Value;
				
				list.Texts.Add (objText);
			} // foreach						        				
				
			
			return list;
			
		}
		
		private XAttribute GetTextAttribute (XElement node)
		{
			foreach (XAttribute attr in node.Attributes()) {
				if (attr.Name != keyAttrId)
					return attr;
			}		
			
			return null;		
		}
		
		#endregion
	}
}

